<?php
/**
 * 大赛初审
 */
namespace Beerus\Modules\DesignerCompetition2024\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use Beerus\Modules\DesignerCompetition2022\Actions\WorkBatchDelete;
use Beerus\Modules\DesignerCompetition2022\Actions\WorkDelete;
use Doraemon\model\ReDesignerCompetition\Audit\DcAuditReviewerHelper;
use Doraemon\model\ReDesignerCompetition\DcAward;
use Doraemon\model\Member;
use Doraemon\model\ReDesignerCompetition\Sign\DcUserInfoHelper;
use Doraemon\model\ReDesignerCompetition\Sign\DcUserSignHelper;
use Doraemon\service\DesignerCompetition\DcCommon;
use Doraemon\service\DesignerCompetition\Sign\Sign2022\ArticleCase;
use Doraemon\service\DesignerCompetition\Sign\Sign2022\Award;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Encore\Admin\Grid\Displayers\DropdownActions;

class FirstAuditController extends AuditBaseController {
    public $iAuditStep = 1; // 初审
    public $iTabAwardId = 0; // 当前tab的奖项id
    const PAGE_SIZE = 20;

    /**
     * 大赛初审列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function index(Request $request, Content $content, $iAwardId) {
        $pageSize = $request->input('per_page', self::PAGE_SIZE);
        $page = $request->input('page', 1);
        $condition = $this->condition($request->all());
        if ($iAwardId == self::MAIN_AWARD_ID_PARENT) {
            $iMainAwardId = $request->get('main_award_id');
            $mixAwardId = $iMainAwardId ?: self::MAIN_AWARD_ID_LIVE_ALONE;
        } else {
            $mixAwardId = $iAwardId;
        }
        $condition['award_id'] = $mixAwardId;
        $this->iTabAwardId = $iAwardId;
        $tab = new Tab();
        $tab->addLink('初筛确认（主奖项）', '/admin/DesignerCompetition2022/first_audit/'.self::MAIN_AWARD_ID_PARENT, $iAwardId == self::MAIN_AWARD_ID_PARENT);
        $tab->addLink('初筛确认（平面）', '/admin/DesignerCompetition2022/first_audit/'.self::SINGLE_AWARD_ID_PLANE, $iAwardId == self::SINGLE_AWARD_ID_PLANE);
        $tab->addLink('初筛确认（软装）', '/admin/DesignerCompetition2022/first_audit/'.self::SINGLE_AWARD_ID_SOFT, $iAwardId == self::SINGLE_AWARD_ID_SOFT);
        $tab->addLink('初筛确认（材料/工艺）', '/admin/DesignerCompetition2022/first_audit/'.self::SINGLE_AWARD_ID_MAKE, $iAwardId == self::SINGLE_AWARD_ID_MAKE);
        return $content
            ->header('大赛初审列表')
            ->body($tab)
            ->row(self::indexGrid($condition, $page, $pageSize));
    }

    public function indexGrid($condition, $page, $pageSize) {
        $total = $this->oAuditWork->countListByCondition($condition);
        $list = $this->oAuditWork->getListByCondition($condition, $page, $pageSize);
        if (!empty($list)) {
            self::formatSignList($list);
        }
        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize,
        ]);

        // 获取单项奖
        $awardList = DcAward::getAllAwardListByAwardYear(self::SIGN_YEAR);
        $awardSelectList = [];
        foreach ($awardList as $awardItem) {
            if ($awardItem['award_type'] == self::AWARD_TYPE_LIST['main_award']) {
                $awardSelectList['main_award'][$awardItem['id']] = $awardItem['award_show_name'];
                continue;
            }
            if ($awardItem['award_type'] == self::AWARD_TYPE_LIST['single_award']) {
                $awardSelectList['single_award'][$awardItem['id']] = $awardItem['award_show_name'];
                continue;
            }
            if ($awardItem['award_type'] == self::AWARD_TYPE_LIST['brand_award']) {
                $awardSelectList['brand_award'][$awardItem['id']] = $awardItem['award_show_name'];
            }
        }
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel, $awardSelectList) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableCreateButton();
                $grid->disableExport();
                $grid->disableRowSelector();
//
                $grid->filter(function (Grid\Filter $filter) use ($awardSelectList) {
                    $filter->disableIdFilter();
                    $options = ['' => '全部', '1' => '是', '2' => '否'];
                    $filter->column(1 / 2, function ($filter) use ($awardSelectList, $options) {
                        $filter->equal('uid', '用户UID');
                        $filter->equal('user_type', '用户身份')->select(self::USER_TYPE_MAP);
                        if (in_array($this->iTabAwardId, self::MAIN_AWARD_ID_LIST)) {
                            $filter->equal('main_award_id', '主奖项')->select($awardSelectList['main_award'])->default(self::MAIN_AWARD_ID_LIVE_ALONE);
                        }
                        $filter->equal('audit_status', '评审结果')->select(self::ADMIN_AUDIT_STATUS_MAP);
                        $filter->equal('is_star', '强烈推荐')->radio($options);
                    });

                    $filter->column(1 / 2, function ($filter) use ($options) {
                        $filter->equal('is_remark', '包含备注')->radio($options);
                        $filter->equal('admin_remark', '备注内容');
                        $filter->equal('recommend_cnt', '领航员总推荐次数');
                        $filter->equal('star_cnt', '领航员总强推次数');
                        $filter->equal('sign_id', '报名id');
                    });
                    $filter->expand();
                });
//
                $grid->column('sign_id', '报名id')->width(70);
                $grid->column('user_info', '用户信息')->width(140)->display(function () {
                    $userInfo[] = 'uid：' . $this->uid;
                    $userInfo[] = '昵称：<a href="https://frieza.haohaozhu.me/admin/user/Detail/' . $this->uid . '" target="_blank">' . $this->nick . '</a>';
                    $userInfo[] = '身份：' . $this->user_type;
                    return implode('<br/>', $userInfo);
                });

                $grid->column('competition_info', '参赛信息')->width(240)->display(function () {
                    $competition_info[] = '城市：' . $this->city;
                    $competition_info[] = '类型：<br/>' . implode('<br/>', $this->main_award);
                    if (isset($this->single_award)) {
                        $competition_info[] = '单项：<br/>' . implode('<br/>', $this->single_award);
                    }
                    if (isset($this->brand_award)) {
                        $competition_info[] = '品牌：<br/>' . implode('<br/>', $this->brand_award);
                    }
                    $competition_info[] = '报名时间：' . $this->sign_time;
                    $competition_info[] = '已入围作品数：' . (!$this->confirm_num ? 0 : "<b style='color: red'>" .$this->confirm_num. "</b>");
                    return implode('<br/>', $competition_info);
                });
//
                $grid->column('work_link', '作品链接')->width(210)->display(function () {
                    $open = isset($this->work_name) ? '<a class="fa " href="javascript:layer.open(
                        {
                            type: 2,
                            title: \'预览\', 
                            maxmin: true, 
                            area: [\'350px\', \'700px\'],
                            fixed: false,
                            offset: \'r\',
                            content: \'' . $this->link . '\' 
                        });">' . htmlentities($this->work_name) . '</a>' : "";
                    $img = "<img width='200' height='200' src='{$this->work_pic_url}'>";
                    return implode('<br/>', [$img, $open]);

                });
                $grid->column('work_info', '作品信息')->width(300)->display(function () {
                    $work_info = [];
                    $work_info[] = '居室：' . self::ROOM_NUM_TYPE_NAME[$this->room_num_type];
                    $work_info[] = '总造价：' . $this->total_price . '万元';
                    $work_info[] = '地区：' . $this->house_area;
                    $work_info[] = '常住人口：' . $this->people_scale .'人';
                    $work_info[] = '家庭关系：' . $this->family_relation;
                    $work_info[] = '人均面积：' . $this->average_space . '平米/人';
                    $work_info[] = '项目完成时间：' . $this->finish_date;
                    $work_info[] = '使用面积：' . $this->house_space . '平米';
                    $work_info[] = '合作机构：' . ($this->recommend_organ ? self::RECOMMEND_ORGAN_LIST[$this->recommend_organ] : '无');
                    return implode('<br/>', $work_info);
                });
//
                $grid->column('first_audit_list', '初筛成绩')->width(300)->display(function () {
                    if (empty($this->first_audit_list)) {
                        return '暂无评审';
                    }
                    return implode('<br/>', $this->first_audit_list);
                });

                $grid->column('audit_status', '评审结果')->width(200)->radio(self::ADMIN_AUDIT_STATUS_MAP);
                $grid->column('admin_remark', '备注')->width(200)->editable();
                $grid->setActionClass(DropdownActions::class);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->disableView();
                    $actions->add(new WorkDelete($this->iAuditStep));
                    $actions->add(new WorkBatchDelete($this->iAuditStep));
                });
            }
        );
        return $gridList;
    }

    private function condition($request) {
        $response = [];
        if (!empty($request['uid'])) {
            $response['uid'] = $request['uid'];
        }
        if (!empty($request['user_type'])) {
            $response['user_type'] = $request['user_type'];
        }
        if (!empty($request['sign_id'])) {
            $response['sign_id'] = $request['sign_id'];
        }
        if (isset($request['audit_status']) && $request['audit_status'] !== '') {
            $response['audit_status'] = $request['audit_status'];
        }
        // '' = 全部；1=有备注；2=没有备注
        if (!empty($request['is_remark'])) {
            $response['is_remark'] = $request['is_remark'];
        }
        if (!empty($request['admin_remark'])) {
            $response['admin_remark'] = $request['admin_remark'];
        }
        // '' = 全部；1=强烈推荐；2=否
        if (!empty($request['is_star'])) {
            $response['is_star'] = $request['is_star'];
        }
        if (isset($request['recommend_cnt']) && $request['recommend_cnt'] !== '') {
            $response['recommend_cnt'] = $request['recommend_cnt'];
        }
        if (isset($request['star_cnt']) && $request['star_cnt'] !== '') {
            $response['star_cnt'] = $request['star_cnt'];
        }
        return $response;
    }

    public function save(Request $request, $awardId, $id) {
        $pjax = true;
        $status = true;
        $name = $request->input('name');
        $value = $request->input('value');
        $auditStatus = $request->input('audit_status');

        $message = "修改成功";
        try {
            if (isset($name) && isset($value)) {
                switch ($name) {
                    case 'admin_remark':
                        $pjax = false;
                        if (mb_strlen($value) > 300) {
                            throw new \Exception('最多300字');
                        }
                        $this->oAuditWork->updateRemarkById($id, $value);
                        break;
                    default:
                        throw new \Exception('未开发功能');
                }
            } elseif (isset($auditStatus)) {
                $this->oAuditWork->updateAuditStatusById($id, $auditStatus);
            } else {
                throw new \Exception('缺少参数错误');
            }
        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();

            if (!$pjax) {
                return response()->json(['errors' => [$message]], 422);
            }
        }

        return response()->json(compact('message', 'status'));
    }

    public function formatSignList(&$list) {
        $aUids = array_unique(array_column($list, 'uid'));
        $memberInfo = Member::getUsers($aUids);
        $awardRet = (new Award())->getAllAwardListWithTypeGroup();
        $aSignInfoList = (DcUserSignHelper::getInstance())->getAllSignByIds(array_column($list, 'sign_id'));
        $aSignInfoList = array_combine(array_column($aSignInfoList, 'id'), $aSignInfoList);
        $aCompetitionInfoList = (DcUserInfoHelper::getInstance())->getAllCompetitionByUids($aUids);
        $aCompetitionInfoList = array_combine($aUids, $aCompetitionInfoList);
        $aReviewerList = (DcAuditReviewerHelper::getInstance())->getReviewerListByCondition(['audit_step'=>$this->iAuditStep]);
        $aReviewerUids = array_unique(array_column($aReviewerList, 'reviewer_uid'));
        $aReviewerInfoList = Member::getUserInfoByIds($aReviewerUids);
        foreach ($aReviewerInfoList as $aItem) {
            $aReviewerNickList[$aItem['uid']] = $aItem;
        }
        foreach ($list as &$auditItem) {
            $signInfo = $aSignInfoList[$auditItem['sign_id']];
            $signInfo['work_info'] = json_decode($signInfo['work_info'], true);
            // 用户信息
            $auditItem['nick'] = empty($memberInfo[$signInfo['uid']]['nick']) ? '' : $memberInfo[$signInfo['uid']]['nick'];
            $auditItem['user_type'] = self::USER_TYPE[$memberInfo[$signInfo['uid']]['type']];

            // 参赛信息
            $auditItem['competition_area'] = self::COMPETITION_AREA_NAME[$signInfo['competition_area']];
            $competitionInfo = $aCompetitionInfoList[$signInfo['uid']];
            $auditItem['city'] = \Hhz\AdministrativeRegion\Region::getAreaDetailByCode($competitionInfo['city']);
            $auditItem = array_merge($auditItem, Award::getAllAwardName($signInfo['award_ids'], $awardRet));
            $auditItem['sign_time'] = date('Y-m-d H:i:s', $signInfo['add_time']);
            $auditItem['sign_year'] = date('Y', $signInfo['add_time']);

            // 作品链接
            $auditItem['work_name'] = $signInfo['work_name'];
            $auditItem['average_space'] = $signInfo['average_space'];
            $auditItem['work_pic_url'] = DcCommon::getWorkCoverUrl($signInfo['work_info']['live_photos']);

            $auditItem['link'] = Hhzurl::getDomain() . "/designer/game/2022/detail?sign_id={$signInfo['id']}";

            // 作品信息
            (new ArticleCase())->getArticleInfo($signInfo['article_id'], $signInfo['work_info'], $signInfo['article_from']);
            $auditItem['house_area'] = \Hhz\AdministrativeRegion\Region::getAreaDetailByCode($signInfo['work_info']['house_area']);
            $houseSpace = preg_replace('/[平米|平方米|平|平方|㎡]/', '', $signInfo['work_info']['house_space']);
            $auditItem['family_relation'] = $signInfo['work_info']['family_relation'];
            $auditItem['people_scale'] = $signInfo['work_info']['people_scale'];
            $auditItem['total_price'] = $signInfo['work_info']['total_price'];
            $auditItem['finish_date'] = $signInfo['work_info']['finish_date'];
            $auditItem['house_space'] = $houseSpace;
            $auditItem['room_num_type'] = $signInfo['work_info']['room_num_type'];
            // 已入围作品数
            $confirmSignIdList = $this->oAuditWork->getConfirmWorkSignIdList($signInfo['uid']);
            $auditItem['confirm_num'] = count(array_unique($confirmSignIdList));
                // 初筛成绩
            $reviewerAuditStatusList = $this->oAuditResult->getAuditStatusListBySignId($auditItem['sign_id'], $auditItem['award_id']);
            foreach ($reviewerAuditStatusList as $reviewerAuditInfo) {
                // 强推
                $sStarTxt = $reviewerAuditInfo['is_star'] ? '(强推)' : '';
                $auditItem['first_audit_list'][] = $aReviewerNickList[$reviewerAuditInfo['reviewer_uid']]['nick'] . ':' . self::REVIEWER_AUDIT_STATUS_TXT_MAP[$reviewerAuditInfo['audit_status']] . $sStarTxt;
            }
        }
    }
}
